<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!-- 台账类型菜单 -->
      <el-col :xs="24" :sm="24" :md="3" style="padding: 0; margin-right: 0">
        <el-card shadow="never">
          <div style="
              font-weight: bold;
              margin-bottom: 10px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            ">
            <span>台账类型</span>
            <i v-hasPermi="['cost:materialLedger:typechange']" class="el-icon-plus type-add-icon"
              @click="showAddTypeDialog = true" style="cursor: pointer"></i>
          </div>
          <el-menu :default-active="activeType" @select="handleTypeSelect">
            <el-menu-item v-for="type in ledgerTypes" :key="type.value" :index="type.value" class="custom-menu-item">
              <div class="item-icon">
                <i :class="type.icon"></i>
              </div>
              <el-tooltip class="item-title-tooltip" effect="dark" :content="type.label" placement="top"
                :disabled="!isTextTruncated(type.label)">
                <span class="item-title">
                  {{ type.label }}
                </span>
              </el-tooltip>
              <i v-hasPermi="['cost:materialLedger:typechange']" class="type-delete-icon el-icon-delete"
                @click.stop="handleDeleteType(type)"></i>
            </el-menu-item>
            <!-- 空状态显示 -->
            <div v-if="ledgerTypes.length === 0" style="padding: 20px; text-align: center; color: #909399">
              <i class="el-icon-folder-opened" style="font-size: 24px; margin-bottom: 8px"></i>
              <div>暂无台账类型</div>
              <div style="font-size: 12px; margin-top: 4px">
                点击上方"+"添加台账类型
              </div>
            </div>
          </el-menu>
        </el-card>
      </el-col>
      <!-- 台账详情与原有内容 -->
      <el-col :xs="24" :sm="24" :md="21" style="padding-left: 0; margin-left: 0">
        <el-card shadow="never" class="main-card">
          <!-- 原有表单、表格等内容 -->
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable>
                <el-option v-for="dict in dict.type.review_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属项目" prop="projectId">
              <el-select clearable filterable v-model="queryParams.projectId" placeholder="请选择项目">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['cost:materialLedger:add']">新增</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['cost:materialLedger:edit']">修改</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['cost:materialLedger:remove']">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="success" icon="el-icon-upload2" size="mini" @click="handleImport"
                v-hasPermi="['cost:materialLedger:add']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['cost:materialLedger:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <!-- 颜色说明 -->
          <div class="color-legend" style="margin-bottom: 10px; font-size: 12px; color: #666">
            <span style="margin-right: 15px">
              <span style="
                  display: inline-block;
                  width: 16px;
                  height: 16px;
                  background-color: #fff3cd;
                  border: 1px solid #ddd;
                  margin-right: 5px;
                "></span>
              黄色：录入时间与日期相差超过3天且未审核
            </span>
            <span>
              <span style="
                  display: inline-block;
                  width: 16px;
                  height: 16px;
                  background-color: #f8d7da;
                  border: 1px solid #ddd;
                  margin-right: 5px;
                "></span>
              红色：录入时间与日期相差超过7天且未审核
            </span>
          </div>

          <el-table v-loading="loading" :data="materialLedgerList" @selection-change="handleSelectionChange"
            :row-class-name="getRowClassName">
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column label="日期" width="90" align="center" prop="entryDate">
              <template slot-scope="scope">
                <el-tooltip :content="`录入时间与日期相差 ${calculateDateDiff(
                  scope.row.entryTime,
                  scope.row.entryDate
                )} 天`" placement="top" :disabled="calculateDateDiff(
                  scope.row.entryTime,
                  scope.row.entryDate
                ) <= 3
                  ">
                  <span>{{ scope.row.entryDate }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="名称" align="center" prop="name" />
            <el-table-column label="单据号" align="center" prop="invoiceNumber" />
            <el-table-column label="规格型号" align="center" prop="specModel" />

            <el-table-column label="数量" align="center" prop="quantity" />
            <!-- <el-table-column label="计量单位" align="center" prop="unitOfMeasure" /> -->
            <!-- <el-table-column label="含税单价" align="center" prop="taxInclusivePrice" /> -->
            <el-table-column label="含税金额" align="center" prop="amount" />
            <!-- <el-table-column label="供应商" align="center" prop="supplier" /> -->
            <!-- <el-table-column label="进项税率" width="90" align="center" prop="inputTaxRate">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.input_tax" :value="scope.row.inputTaxRate" />
              </template>
            </el-table-column> -->
            <el-table-column label="不含税金额" width="100" align="center" prop="taxExclusiveCost" />
            <!-- <el-table-column label="增值税" align="center" prop="valueAddedTax" /> -->
            <el-table-column label="审核状态" width="90" align="center" prop="auditStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.review_status" :value="scope.row.auditStatus" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="录入时间" align="center" prop="entryTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.entryTime) }}</span>
              </template>
            </el-table-column> -->

            <!-- <el-table-column label="备注" align="center" prop="remark">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
                  <span
                    style="max-width: 120px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;">{{
                      scope.row.remark }}</span>
                </el-tooltip>
              </template>
            </el-table-column> -->
            <el-table-column label="所属项目" width="180" align="center" prop="projectId">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="getProjectNameById(scope.row.projectId)"
                  placement="top">
                  <span style="
                      max-width: 120px;
                      display: inline-block;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      vertical-align: middle;
                    " :title="getProjectNameById(scope.row.projectId)">
                    {{ getProjectNameById(scope.row.projectId) }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <!-- 审核按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:materialLedger:audit']" size="mini"
                  type="text" icon="el-icon-check" @click="handleAudit(scope.row)">审核</el-button>

                <!-- 取消审核按钮 -->
                <el-button v-else-if="scope.row.auditStatus == 2" v-hasPermi="['cost:materialLedger:unaudit']"
                  size="mini" type="text" icon="el-icon-close" @click="handleCancelAudit(scope.row)">取消审核</el-button>

                <!-- 修改按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:materialLedger:edit']" size="mini"
                  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>

                <!-- 详情按钮 -->
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>

                <!-- 删除按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:materialLedger:remove']" size="mini"
                  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改物料进货台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 项目总金额显示区域 -->
      <div class="amount-display-section">
        <div class="amount-display-label">当前类型项目总含税金额：</div>
        <div class="amount-display-content">
          <span v-if="loadingAmount" class="amount-loading">
            <i class="el-icon-loading"></i> 正在获取...
          </span>
          <span v-else class="amount-value">{{ form.projectAmountTotal !== null && form.projectAmountTotal !== undefined
            ?
            form.projectAmountTotal : '选择项目后自动显示' }}</span>
          <span v-if="!loadingAmount && form.projectAmountTotal !== null && form.projectAmountTotal !== undefined"
            class="amount-unit">元</span>
        </div>
      </div>
      <!-- 项目总数量显示区域 -->
      <div class="amount-display-section" v-if="shouldShowCountTotal">
        <div class="amount-display-label">当前项目类型总数量：</div>
        <div class="amount-display-content">
          <span v-if="loadingCount" class="amount-loading">
            <i class="el-icon-loading"></i> 正在获取...
          </span>
          <span v-else class="amount-value">{{ form.projectCountTotal !== null && form.projectCountTotal !== undefined
            ?
            form.projectCountTotal : '选择项目后自动显示' }}</span>
          <span v-if="!loadingCount && form.projectCountTotal !== null && form.projectCountTotal !== undefined"
            class="amount-unit"></span>
        </div>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%" @change="handleProjectChange">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="审核状态">
              <el-radio-group v-model="form.auditStatus">
                <el-radio v-for="dict in dict.type.review_status" :key="dict.value" :label="parseInt(dict.value)">{{
                  dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="日期" prop="entryDate">
              <el-date-picker clearable v-model="form.entryDate" type="date" value-format="yyyy-MM-dd"
                format="yyyy-MM-dd" placeholder="请选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specModel">
              <el-input v-model="form.specModel" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据号" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入单据号" />
            </el-form-item>
          </el-col>
        </el-row>



        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进项税率" prop="inputTaxRate">
              <el-select v-model="form.inputTaxRate" placeholder="请选择进项税率" filterable style="width: 100%">
                <el-option v-for="dict in dict.type.input_tax" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入数量" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="含税单价" prop="taxInclusivePrice">
              <el-input v-model="form.taxInclusivePrice" placeholder="请输入含税单价" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运费" prop="shippingFee">
              <el-input v-model="form.shippingFee" placeholder="请输入运费" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扣款" prop="deduction">
              <el-input v-model="form.deduction" placeholder="请输入扣款" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="8">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="8">
            <el-form-item label="进项税率" prop="inputTaxRate">
              <el-select v-model="form.inputTaxRate" placeholder="请选择进项税率" filterable style="width: 100%">
                <el-option v-for="dict in dict.type.input_tax" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="8">
            <el-form-item label="不含税成本" prop="taxExclusiveCost">
              <el-input v-model="form.taxExclusiveCost" placeholder="请输入不含税成本" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="增值税" prop="valueAddedTax">
              <el-input v-model="form.valueAddedTax" placeholder="请输入增值税" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="录入时间" prop="entryTime">
              <el-date-picker clearable v-model="form.entryTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择录入时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请输入计量单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
            </el-form-item>
          </el-col>

        </el-row>

        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item> -->

        <el-form-item label="上传凭证" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="upload" drag action="#" :auto-upload="true" list-type="picture-card"
              :on-change="onUploadChange" :on-remove="onUploadRemove" :on-exceed="onUploadExceed"
              :file-list="uploadFileList" accept="image/*" class="upload-component" :http-request="handleCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅用于随单据上传的图片凭证，支持多张
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="上传文件" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="fileUpload" drag action="#" :auto-upload="true" list-type="text"
              :on-change="onFileUploadChange" :on-remove="onFileUploadRemove" :on-exceed="onFileUploadExceed"
              :file-list="uploadDocumentList" accept=".pdf,.doc,.docx" class="file-upload-component"
              :http-request="handleFileCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅支持PDF和Word文件，支持多个文件
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加台账类型对话框 -->
    <el-dialog title="添加台账类型" :visible.sync="showAddTypeDialog" width="500px" append-to-body
      @close="addTypeForm.typeName = ''">
      <el-form :model="addTypeForm" @submit.native.prevent>
        <el-form-item label="类型名称" label-width="80px">
          <el-input v-model="addTypeForm.typeName" placeholder="请输入类型名称" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddTypeDialog = false">取 消</el-button>
        <el-button type="primary" :loading="addTypeLoading" @click="handleAddType">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="导入物料进货台账" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="所属项目" prop="porjectId">
          <el-select v-model="importForm.porjectId" placeholder="请选择所属项目" style="width: 100%">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="台账类型" prop="ledgerTypeId">
          <el-input :value="getCurrentTypeName()" placeholder="当前选中的台账类型" disabled style="width: 100%">
            <template slot="append">
              <el-tag size="small" type="info">{{ getCurrentTypeName() }}</el-tag>
            </template>
          </el-input>
        </el-form-item> -->
        <el-form-item label="选择文件" prop="file">
          <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :on-change="handleFileChange" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="
                  font-size: 12px;
                  vertical-align: baseline;
                  margin-left: 8px;
                " @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="detailOpen" width="900px" :show-close="true" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">物料进货台账详情</div>
      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">填报日期</th>
              <td class="value">{{ detailForm.entryDate }}</td>
            </tr>
            <tr>
              <th class="left-align">名称</th>
              <td class="value">{{ detailForm.name }}</td>
            </tr>
            <tr>
              <th class="left-align">单据号</th>
              <td class="value">{{ detailForm.invoiceNumber }}</td>
            </tr>
            <tr>
              <th class="left-align">规格型号</th>
              <td class="value">{{ detailForm.specModel }}</td>
            </tr>

            <tr>
              <th class="left-align">数量</th>
              <td class="value">{{ detailForm.quantity }}</td>
            </tr>
            <tr>
              <th class="left-align">计量单位</th>
              <td class="value">{{ detailForm.unitOfMeasure }}</td>
            </tr>
            <tr>
              <th class="left-align">含税单价</th>
              <td class="value">{{ detailForm.taxInclusivePrice }}</td>
            </tr>
            <tr>
              <th class="left-align">含税金额</th>
              <td class="value">{{ detailForm.amount }}</td>
            </tr>

            <tr>
              <th class="left-align">录入时间</th>
              <td class="value">{{ detailForm.entryTime }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">供应商</th>
              <td class="value">{{ detailForm.supplier }}</td>
            </tr>
            <tr>
              <th class="left-align">进项税率</th>
              <td class="value">
                <dict-tag :options="dict.type.input_tax" :value="detailForm.inputTaxRate" />
              </td>
            </tr>
            <tr>
              <th class="left-align">不含税成本</th>
              <td class="value">{{ detailForm.taxExclusiveCost }}</td>
            </tr>
            <tr>
              <th class="left-align">增值税</th>
              <td class="value">{{ detailForm.valueAddedTax }}</td>
            </tr>
            <tr>
              <th class="left-align">审核状态</th>
              <td class="value">
                <dict-tag :options="dict.type.review_status" :value="detailForm.auditStatus" />
              </td>
            </tr>
            <tr>
              <th class="left-align">所属项目</th>
              <td class="value">
                {{ getProjectNameById(detailForm.projectId) }}
              </td>
            </tr>
            <tr>
              <th class="left-align">运费</th>
              <td class="value">{{ detailForm.shippingFee }}</td>
            </tr>
            <tr>
              <th class="left-align">扣款</th>
              <td class="value">{{ detailForm.deduction }}</td>
            </tr>
            <tr>
              <th class="left-align">备注</th>
              <td class="value">{{ detailForm.remark }}</td>
            </tr>
          </table>
        </div>
      </div>
      <!-- 图片展示区域 -->
      <div class="daily-section-title">凭证信息</div>
      <div v-if="detailImageUrls && detailImageUrls.length > 0" class="image-display-container">
        <div v-for="(url, index) in detailImageUrls" :key="`display-${index}`" class="image-item">
          <el-image :src="url" :preview-src-list="detailImageUrls" fit="cover" class="detail-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>

      <!-- 文件展示区域 -->
      <div v-if="detailFileList && detailFileList.length > 0" class="daily-section-title">附件信息</div>
      <div v-if="detailFileList && detailFileList.length > 0" class="file-display-container">
        <div v-for="(file, index) in detailFileList" :key="`file-${index}`" class="file-item">
          <div class="file-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ file.fileName }}</span>
            <div class="file-actions">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="handleFileDownload(file)">
                下载
              </el-button>
              <el-button type="success" size="mini" icon="el-icon-view" @click="handleFilePreview(file)">
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <!-- 文件预览弹框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="60vw" top="5vh" :title="getPreviewTitle()"
      @close="previewFile = null">
      <div v-if="previewFile">
        <!-- 图片预览 -->
        <el-image v-if="getFileType(previewFile.fileName) === 'image'" :src="previewFile.downloadUrl"
          :preview-src-list="[previewFile.downloadUrl]" fit="contain"
          style="max-width:100%;max-height:70vh;display:block;margin:auto;cursor:pointer;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <!-- 文档/PDF/Word/Excel 预览：直接用iframe打开 -->
        <iframe v-else-if="['pdf', 'word', 'excel', 'ppt'].includes(getFileType(previewFile.fileName))"
          :src="previewFile.downloadUrl" style="width:100%;height:70vh;border:none;"></iframe>
        <!-- 其他类型提示 -->
        <div v-else style="text-align:center;padding:40px 0;color:#888;">
          暂不支持该类型文件的在线预览，请下载后查看。
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaterialLedger,
  getMaterialLedger,
  delMaterialLedger,
  addMaterialLedger,
  updateMaterialLedger,
  addImg,
  delImg,
  fileImport,
  getAmountTotal,
  getCountTotal
} from "@/api/cost/materialLedger";
import {
  listMaterialLedgerType,
  addMaterialLedgerType,
  delMaterialLedgerType,
} from "@/api/cost/materialLedgerType";
import { listAllProjectContractInfo } from "@/api/production/projectContractInfo";
import { fileLinkTransfer, fileLinkLooking } from "@/api/production/projectFileInfo";

// 日期处理工具函数
const formatDate = (dateValue) => {
  if (!dateValue) return null;

  let date;
  if (typeof dateValue === "string") {
    // 处理字符串格式的日期
    if (dateValue.includes("T") || dateValue.includes("Z")) {
      date = new Date(dateValue);
    } else if (dateValue.match(/^\d{4}-\d{2}-\d{2}$/)) {
      // 如果是 "yyyy-MM-dd" 格式，直接返回
      return dateValue;
    } else if (dateValue.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
      // 如果是 "yyyy-MM-dd HH:mm:ss" 格式，提取日期部分
      return dateValue.split(" ")[0];
    } else {
      // 其他格式，尝试转换为Date对象
      date = new Date(dateValue);
    }
  } else if (dateValue instanceof Date) {
    date = dateValue;
  } else {
    // 其他情况，尝试转换为Date对象
    date = new Date(dateValue);
  }

  if (isNaN(date.getTime())) {
    return null;
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const formatDateTime = (dateValue) => {
  if (!dateValue) return null;

  let date;
  if (typeof dateValue === "string") {
    if (dateValue.includes("T") || dateValue.includes("Z")) {
      date = new Date(dateValue);
    } else if (dateValue.match(/^\d{4}-\d{2}-\d{2}$/)) {
      // 如果是 "yyyy-MM-dd" 格式，转换为 "yyyy-MM-dd HH:mm:ss" 格式
      return `${dateValue} 00:00:00`;
    } else if (dateValue.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
      // 如果已经是 "yyyy-MM-dd HH:mm:ss" 格式，直接返回
      return dateValue;
    } else {
      // 其他格式，尝试转换为Date对象
      date = new Date(dateValue);
    }
  } else if (dateValue instanceof Date) {
    date = dateValue;
  } else {
    date = new Date(dateValue);
  }

  if (isNaN(date.getTime())) {
    return null;
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

export default {
  name: "MaterialLedger",
  dicts: ["review_status", "input_tax"],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料进货台账表格数据
      materialLedgerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 台账类型相关数据
      ledgerTypes: [],
      activeType: "",
      showAddTypeDialog: false,
      addTypeForm: {
        typeName: "",
      },
      addTypeLoading: false,
      typeParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        remark: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditStatus: null,
        entryDate: null,
        entryTime: null,
        invoiceNumber: null,
        specModel: null,
        quantity: null,
        unitOfMeasure: null,
        taxInclusivePrice: null,
        amount: null,
        supplier: null,
        inputTaxRate: null,
        taxExclusiveCost: null,
        valueAddedTax: null,
        remark: null,
        ledgerTypeId: null,
        projectId: null,
      },
      // 表单参数
      form: {
        imageList: [], // 存储转换后的图片链接数组
        shippingFee: null, // 运费
        deduction: null, // 扣款
        projectAmountTotal: null, // 项目总含税金额
        projectCountTotal: null, // 项目总数量
      },
      // 加载状态
      loadingAmount: false,
      loadingCount: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        id: [{ required: true, message: "主键ID不能为空", trigger: "blur" }],
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "blur" },
        ],
        shippingFee: [
          { required: true, message: "填报运费不能为空", trigger: "blur" },
        ],
        deduction: [
          { required: true, message: "填报扣款不能为空", trigger: "blur" },
        ],
        entryDate: [
          { required: true, message: "填报日期不能为空", trigger: "blur" },
        ],
        entryTime: [
          { required: true, message: "录入时间不能为空", trigger: "blur" },
        ],
        invoiceNumber: [
          { required: true, message: "单据号不能为空", trigger: "blur" },
        ],
        specModel: [
          { required: true, message: "规格型号不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        unitOfMeasure: [
          { required: true, message: "计量单位不能为空", trigger: "blur" },
        ],
        taxInclusivePrice: [
          { required: true, message: "含税单价不能为空", trigger: "blur" },
        ],
        amount: [{ required: true, message: "金额不能为空", trigger: "blur" }],
        supplier: [
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        inputTaxRate: [
          { required: true, message: "进项税率不能为空", trigger: "change" },
        ],
        taxExclusiveCost: [
          { required: true, message: "不含税成本不能为空", trigger: "blur" },
        ],
        valueAddedTax: [
          { required: true, message: "增值税不能为空", trigger: "blur" },
        ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
        ledgerTypeId: [
          { required: true, message: "台账类型ID不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "所属项目id不能为空", trigger: "blur" },
        ],
      },
      projectOptions: [],
      detailOpen: false,
      detailForm: {},
      // 详情页面的图片链接
      detailImageUrls: [],
      // 详情页面的文件列表
      detailFileList: [],
      // 文件预览相关
      previewDialogVisible: false,
      previewFile: null,
      // 处理后的图片链接（用于回显）
      processedImageList: [],
      // 上传文件列表（图片）
      uploadFileList: [],
      // 上传文件列表（文档）
      uploadDocumentList: [],
      // 导入弹窗相关
      importOpen: false,
      importForm: {
        porjectId: null,
        ledgerTypeId: null,
        file: null,
      },
      importRules: {
        porjectId: [
          { required: true, message: "请选择所属项目", trigger: "change" },
        ],
        file: [
          { required: true, message: "请选择要导入的文件", trigger: "change" },
        ],
      },
      // 导入上传相关
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
    };
  },
  async created() {

    await this.fetchProjectOptions();
    await this.getTypeList();
    // 设置上传请求头
    this.upload.headers = {
      Authorization: "Bearer " + this.$store.getters.token,
    };

    console.log("11", this.$store.getters.permissions);
  },
  computed: {
    /** 判断是否应该显示数量统计（仅当台账类型为58,58,60,61时显示） */
    shouldShowCountTotal() {
      const allowedTypes = ['58', '59', '60', '61'];
      return this.activeType && allowedTypes.includes(String(this.activeType));
    },
  },
  methods: {
    /** 查询台账类型列表 */
    async getTypeList() {
      // 添加menuType参数
      const params = {
        ...this.typeParams,
        menuType: "materialLedger",
      };
      try {
        const response = await listMaterialLedgerType(params);
        this.ledgerTypes = [];
        response.rows.forEach((item) => {
          this.ledgerTypes.push({
            label: item.typeName,
            value: String(item.id),
            icon: "el-icon-document",
          });
        });

        // 检查台账类型列表是否为空
        if (this.ledgerTypes.length > 0) {
          this.activeType = this.ledgerTypes[0].value;
          this.queryParams.ledgerTypeId = this.ledgerTypes[0].value;
        } else {
          // 如果没有台账类型，设置为null或空字符串
          this.activeType = "";
          this.queryParams.ledgerTypeId = null;
        }

        this.getList(); // 类型变动后自动刷新列表
      } catch (error) {
        console.error("获取台账类型列表失败:", error);
        // 发生错误时也设置为空
        this.ledgerTypes = [];
        this.activeType = "";
        this.queryParams.ledgerTypeId = null;
        this.getList(); // 仍然尝试获取台账列表
      }
    },
    /** 查询物料进货台账列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listMaterialLedger(this.queryParams);
        // 统一后端返回与前端使用的类型：进项税率统一为字符串
        this.materialLedgerList = (response.rows || []).map((item) => ({
          ...item,
          inputTaxRate:
            item &&
              item.inputTaxRate !== null &&
              item.inputTaxRate !== undefined
              ? String(item.inputTaxRate)
              : item.inputTaxRate,
        }));
        this.total = response.total;
      } catch (error) {
        this.$message.error("获取列表失败");
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        auditStatus: null,
        entryDate: null,
        entryTime: null,
        invoiceNumber: null,
        specModel: null,
        name: null,
        quantity: null,
        unitOfMeasure: null,
        taxInclusivePrice: null,
        amount: null,
        supplier: null,
        inputTaxRate: null,
        taxExclusiveCost: null,
        valueAddedTax: null,
        remark: null,
        ledgerTypeId: null,
        projectId: null,
        imageList: [], // 重置图片链接数组
        shippingFee: null, // 重置运费
        deduction: null, // 重置扣款
        projectAmountTotal: null, // 重置项目总含税金额
        projectCountTotal: null, // 重置项目总数量
      };
      this.uploadFileList = [];
      this.uploadDocumentList = []; // 重置文档上传列表
      this.processedImageList = []; // 重置处理后的图片链接
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    async handleQuery() {
      this.queryParams.pageNum = 1;
      await this.getList();
    },
    /** 重置按钮操作 */
    async resetQuery() {
      this.resetForm("queryForm");
      // 重置类型为第一个（如有）
      if (this.ledgerTypes && this.ledgerTypes.length > 0) {
        this.activeType = this.ledgerTypes[0].value;
        this.queryParams.ledgerTypeId = this.ledgerTypes[0].value;
      } else {
        this.activeType = "";
        this.queryParams.ledgerTypeId = null;
      }
      await this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      if (!this.activeType) {
        this.$message.warning("请先选择劳务类型");
        return;
      }
      this.reset();
      // 新增时录入时间默认今天
      const today = new Date();
      this.form.entryTime = formatDateTime(today);
      this.form.entryDate = formatDate(today);
      // 新增时默认带上当前选中的台账类型id
      this.form.ledgerTypeId = this.activeType;
      this.open = true;
      this.title = "添加物料进货台账";

      // 如果已经选择了项目，自动获取总金额
      if (this.form.projectId) {
        await this.handleProjectChange(this.form.projectId);
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      try {
        const response = await getMaterialLedger(id);
        this.form = response.data;
        // 使用工具函数处理日期格式
        this.form.entryDate = formatDate(this.form.entryDate);
        this.form.entryTime = formatDateTime(this.form.entryTime);
        // 统一进项税率类型为字符串，便于与字典选项匹配
        if (
          this.form &&
          this.form.inputTaxRate !== null &&
          this.form.inputTaxRate !== undefined
        ) {
          this.form.inputTaxRate = String(this.form.inputTaxRate);
        }

        // 处理图片回显
        await this.processImageListForDisplay();

        this.open = true;
        this.title = "修改物料进货台账";
      } catch (error) {
        console.error("修改 - 获取数据失败:", error);
        this.$message.error("获取数据失败");
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 先根据含税单价与数量计算金额，避免校验时金额为空
      const price = Number(this.form.taxInclusivePrice) || 0;
      const qty = Number(this.form.quantity) || 0;
      this.form.amount = +(price * qty).toFixed(2);

      const valid = await this.$refs["form"].validate();
      if (!valid) return;

      try {
        // 添加时带上当前选中的台账类型id
        if (!this.form.id) {
          this.form.ledgerTypeId = this.activeType;
        }
        // 确保日期格式正确
        if (this.form.entryDate && !this.form.entryDate.includes(" ")) {
          this.form.entryDate = `${this.form.entryDate} 00:00:00`;
        }

        // 确保图片列表数据被包含
        if (!this.form.imageList) {
          this.form.imageList = [];
        }

        // 构造纯净的请求载荷，确保 amount 被携带且为数值
        const payload = {
          ...this.form,
          quantity: Number(this.form.quantity) || 0,
          taxInclusivePrice: Number(this.form.taxInclusivePrice) || 0,
          amount: Number(this.form.amount) || 0,
        };

        if (this.form.id != null) {
          await updateMaterialLedger(payload);
          this.$modal.msgSuccess("修改成功");
        } else {
          this.form.auditStatus = 1;
          payload.auditStatus = 1;
          await addMaterialLedger(payload);
          this.$modal.msgSuccess("新增成功");
        }

        this.open = false;
        this.getList();
      } catch (error) {
        this.$message.error("操作失败");
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const ids = row.id || this.ids;

      try {
        await this.$modal.confirm("是否确认删除？");
        await delMaterialLedger(ids);
        this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        // 用户取消删除或删除失败时静默处理
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cost/materialLedger/export",
        {
          ...this.queryParams,
        },
        `materialLedger_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载导入模板 */
    importTemplate() {
      const url =
        "https://ggkt-1319488159.cos.ap-beijing.myqcloud.com/%E6%88%90%E6%9C%AC%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88/%E7%89%A9%E6%96%99%E8%BF%9B%E8%B4%A7%E5%8F%B0%E8%B4%A6%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx";
      window.open(url, "_blank");
    },
    // 台账类型相关方法
    async handleTypeSelect(val) {
      this.activeType = String(val);
      this.queryParams.ledgerTypeId = String(val);
      this.form.ledgerTypeId = String(val);
      await this.getList();
    },
    async handleDeleteType(type) {
      // 判断该类型下是否有台账数据
      const hasData =
        this.materialLedgerList &&
        this.materialLedgerList.some((item) => item.ledgerTypeId == type.value);
      if (hasData) {
        this.$message.warning("该类型下有台账数据，不能删除！");
        return;
      }
      try {
        await this.$confirm(`是否确认删除台账类型"${type.label}"？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await delMaterialLedgerType(type.value);
        this.$message.success("删除成功");
        // 重新获取类型列表，自动处理 activeType 和 ledgerTypeId
        this.getTypeList();
      } catch (error) {
        // 用户取消删除或删除失败时静默处理
      }
    },
    async handleAddType() {
      if (!this.addTypeForm.typeName.trim()) {
        this.$message.warning("请输入类型名称");
        return;
      }
      this.addTypeLoading = true;
      try {
        await addMaterialLedgerType({
          typeName: this.addTypeForm.typeName,
          menuType: "materialLedger",
        });
        this.$message.success("添加成功");
        this.showAddTypeDialog = false;
        this.addTypeForm.typeName = "";
        this.getTypeList();
      } catch (error) {
        this.$message.error("添加失败");
      } finally {
        this.addTypeLoading = false;
      }
    },
    // 检测文本是否被截断
    isTextTruncated(text) {
      if (!text) return false;

      // 创建临时元素来测量文本实际宽度
      const tempElement = document.createElement("span");
      tempElement.style.cssText = `
        position: absolute;
        visibility: hidden;
        white-space: nowrap;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
        width: auto;
        height: auto;
      `;
      tempElement.textContent = text;
      document.body.appendChild(tempElement);

      const textWidth = tempElement.offsetWidth;
      const containerWidth = 120; // 容器宽度

      document.body.removeChild(tempElement);

      return textWidth > containerWidth;
    },
    async fetchProjectOptions() {
      // 获取所有项目列表
      try {
        const res = await listAllProjectContractInfo();
        this.projectOptions = res.data || [];
      } catch (error) {
        this.$message.error("获取项目列表失败");
      }
    },
    /** 根据项目ID获取项目名称 */
    getProjectNameById(projectId) {
      const item = this.projectOptions.find((p) => p.id == projectId);
      return String(item ? item.projectName : (projectId ?? ''));
    },
    /** 处理项目选择变化 */
    async handleProjectChange(projectId) {
      if (!projectId || !this.activeType) {
        this.form.projectAmountTotal = null;
        this.form.projectCountTotal = null;
        return;
      }
      // 显示加载状态
      this.loadingAmount = true;

      // 只有符合条件的类型才显示数量统计的加载状态
      if (this.shouldShowCountTotal) {
        this.loadingCount = true;
      }

      try {
        // 构建请求数组
        const requests = [getAmountTotal(this.activeType, projectId)];

        // 只有符合条件的类型才调用数量统计接口
        if (this.shouldShowCountTotal) {
          requests.push(getCountTotal(this.activeType, projectId));
        }

        // 执行请求
        const responses = await Promise.all(requests);
        this.form.projectAmountTotal = responses[0].data || 0;

        // 只有调用了数量接口才设置数量
        if (this.shouldShowCountTotal) {
          this.form.projectCountTotal = responses[1].data || 0;
        } else {
          this.form.projectCountTotal = null;
        }
      } catch (error) {
        console.error("获取项目统计数据失败:", error);
        this.$message.error("获取项目统计数据失败");
        this.form.projectAmountTotal = null;
        this.form.projectCountTotal = null;
      } finally {
        // 无论成功失败都要关闭加载状态
        this.loadingAmount = false;
        if (this.shouldShowCountTotal) {
          this.loadingCount = false;
        }
      }
    },
    async handleDetail(row) {
      try {
        const response = await getMaterialLedger(row.id);
        this.detailForm = response.data;
        // 确保详情弹窗中的日期格式正确
        this.detailForm.entryDate = formatDate(this.detailForm.entryDate);
        // this.detailForm.entryTime = formatDateTime(this.detailForm.entryTime);
        // 统一详情中进项税率的数据类型为字符串
        if (
          this.detailForm &&
          this.detailForm.inputTaxRate !== null &&
          this.detailForm.inputTaxRate !== undefined
        ) {
          this.detailForm.inputTaxRate = String(this.detailForm.inputTaxRate);
        }

        // 处理图片和文件链接转换
        await this.processDetailImageAndFiles();

        this.detailOpen = true;
      } catch (error) {
        console.error("获取详情失败:", error);
        this.$message.error("获取详情失败");
      }
    },
    async handleAudit(row) {
      try {
        const data = { ...row, auditStatus: 2, clickAudit: true };
        await updateMaterialLedger(data);
        this.$modal.msgSuccess("审核成功");
        this.getList();
      } catch (error) {
        this.$message.error("审核失败");
      }
    },
    async handleCancelAudit(row) {
      try {
        const data = { ...row, auditStatus: 1, clickAudit: true };
        await updateMaterialLedger(data);
        this.$modal.msgSuccess("已取消审核");
        this.getList();
      } catch (error) {
        this.$message.error("取消审核失败");
      }
    },
    // 处理详情页面的图片和文件
    async processDetailImageAndFiles() {
      if (!this.detailForm.imageList?.length) {
        this.detailImageUrls = [];
        this.detailFileList = [];
        return;
      }

      this.detailImageUrls = [];
      this.detailFileList = [];

      for (let i = 0; i < this.detailForm.imageList.length; i++) {
        const url = this.detailForm.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件
            this.detailImageUrls.push(displayUrl);
          } else {
            // 文档文件
            this.detailFileList.push({
              fileName: fileName,
              downloadUrl: url,
              displayUrl: displayUrl,
              fileType: fileType
            });
          }
        } catch (error) {
          console.error(`处理文件失败:`, error);
        }
      }
    },
    // 获取文件类型
    getFileType(fileName) {
      if (!fileName) return 'unknown';
      const extension = fileName.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
      const pdfTypes = ['pdf'];
      const wordTypes = ['doc', 'docx'];
      const excelTypes = ['xls', 'xlsx'];
      const pptTypes = ['ppt', 'pptx'];

      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      if (wordTypes.includes(extension)) return 'word';
      if (excelTypes.includes(extension)) return 'excel';
      if (pptTypes.includes(extension)) return 'ppt';
      return 'unknown';
    },
    // 判断是否为图片文件
    isImageFile(fileType) {
      return fileType === 'image';
    },
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },
    // 文件下载
    async handleFileDownload(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的下载链接");
        return;
      }
      try {
        const res = await fileLinkTransfer(file.downloadUrl);
        const newUrl = res.data.url;
        if (!newUrl) {
          this.$message.error("获取下载链接失败");
          return;
        }
        // 创建a标签下载
        const a = document.createElement("a");
        a.href = newUrl;
        a.download = file.fileName || "";
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        this.$message.error("下载失败");
      }
    },
    // 文件预览
    async handleFilePreview(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的预览链接");
        return;
      }
      try {
        let newUrl = '';
        const fileType = this.getFileType(file.fileName);

        if (fileType === 'image') {
          // 图片直接使用fileLinkTransfer
          const res = await fileLinkTransfer(file.downloadUrl);
          newUrl = res.data.url;
        } else if (['pdf', 'word', 'excel', 'ppt'].includes(fileType)) {
          // 文档使用fileLinkLooking
          const res = await fileLinkLooking(file.downloadUrl);
          newUrl = res.data.url;
        } else {
          newUrl = file.downloadUrl;
        }

        if (!newUrl) {
          this.$message.error("获取预览链接失败");
          return;
        }

        this.previewFile = { ...file, downloadUrl: newUrl };
        this.previewDialogVisible = true;
      } catch (e) {
        this.$message.error("预览失败");
      }
    },
    // 获取预览标题
    getPreviewTitle() {
      if (this.previewFile && this.previewFile.fileName) {
        return this.previewFile.fileName;
      }
      return "文件预览";
    },
    // 计算日期差（天数）
    calculateDateDiff(entryTime, entryDate) {
      if (!entryTime || !entryDate) return 0;

      try {
        // 解析录入时间
        let entryTimeDate;
        if (typeof entryTime === "string") {
          if (entryTime.includes("T") || entryTime.includes("Z")) {
            entryTimeDate = new Date(entryTime);
          } else {
            entryTimeDate = new Date(entryTime);
          }
        } else {
          entryTimeDate = new Date(entryTime);
        }

        // 解析日期
        let entryDateObj;
        if (typeof entryDate === "string") {
          if (entryDate.includes("T") || entryDate.includes("Z")) {
            entryDateObj = new Date(entryDate);
          } else {
            entryDateObj = new Date(entryDate);
          }
        } else {
          entryDateObj = new Date(entryDate);
        }

        if (isNaN(entryTimeDate.getTime()) || isNaN(entryDateObj.getTime())) {
          return 0;
        }

        // 计算时间差（毫秒）
        const timeDiff = entryTimeDate.getTime() - entryDateObj.getTime();
        // 转换为天数，使用绝对值确保正数
        const daysDiff = Math.abs(Math.ceil(timeDiff / (1000 * 60 * 60 * 24)));

        return daysDiff;
      } catch (error) {
        console.error("计算日期差时出错:", error);
        return 0;
      }
    },
    // 获取行样式类名
    getRowClassName({ row, rowIndex }) {
      // 仅未审核时显示颜色
      if (row.auditStatus != 1) {
        return "";
      }

      const daysDiff = this.calculateDateDiff(row.entryTime, row.entryDate);

      if (daysDiff > 7) {
        return "row-red";
      } else if (daysDiff > 3) {
        return "row-yellow";
      }

      return "";
    },
    // 上传相关方法
    onUploadChange(file, fileList) {
      this.uploadFileList = fileList;
    },
    // 自定义上传：调用 addImg 接口将文件转为图片链接
    async handleCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的图片链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "image.jpg",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadFileList = [...this.uploadFileList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("图片上传失败");
        param?.onError?.(err);
      }
    },
    // 删除图片：仅本地移除，不调用后端
    async onUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadFileList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadFileList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadFileList = fileList;
    },
    onUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 张图片，已选择 ${files.length} 张`
      );
    },
    // 文件上传相关方法
    onFileUploadChange(file, fileList) {
      this.uploadDocumentList = fileList;
    },
    // 自定义文件上传：调用 addImg 接口将文件转为文件链接
    async handleFileCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      // 检查文件类型
      const allowedTypes = ['.pdf', '.doc', '.docx'];
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
      if (!allowedTypes.includes(fileExtension)) {
        this.$message.error("只支持PDF和Word文件");
        param?.onError?.(new Error("文件类型不支持"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的文件链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "document.pdf",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadDocumentList = [...this.uploadDocumentList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("文件上传失败");
        param?.onError?.(err);
      }
    },
    // 删除文件：仅本地移除，不调用后端
    async onFileUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadDocumentList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadDocumentList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadDocumentList = fileList;
    },
    onFileUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 个文件，已选择 ${files.length} 个`
      );
    },
    // 获取可访问的图片链接（用于显示）
    async getDisplayImageUrl(url) {
      if (!url) {
        return "";
      }

      try {
        const {
          data: { url: accessibleUrl },
        } = await fileLinkTransfer(url);
        return accessibleUrl || url;
      } catch (error) {
        console.error("getDisplayImageUrl - 转换失败:", error);
        return url;
      }
    },
    // 获取图片链接列表（用于显示）
    async getDisplayImageUrlList(urls) {
      if (!Array.isArray(urls) || urls.length === 0) return [];

      return Promise.all(urls.map((url) => this.getDisplayImageUrl(url)));
    },
    // 处理图片列表用于显示
    async processImageListForDisplay() {
      if (!this.form.imageList?.length) {
        this.form.imageList = [];
        this.uploadFileList = [];
        this.uploadDocumentList = [];
        return;
      }

      this.uploadFileList = [];
      this.uploadDocumentList = [];

      for (let i = 0; i < this.form.imageList.length; i++) {
        const url = this.form.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件，添加到图片上传列表，保存原始路径用于删除
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url: displayUrl,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            // 文档文件，添加到文件上传列表，保存原始路径用于删除
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url: displayUrl,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        } catch (error) {
          console.error(`processImageListForDisplay - 转换失败:`, error);
          // 转换失败时，根据文件名判断类型
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        }
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      if (!this.activeType) {
        this.$message.warning("请先选择劳务类型");
        return;
      }
      this.importOpen = true;
      this.resetImport();
    },
    /** 取消导入 */
    cancelImport() {
      this.importOpen = false;
      this.resetImport();
    },
    /** 重置导入表单 */
    resetImport() {
      this.importForm = {
        porjectId: null,
        file: null,
      };
      // 清空上传组件的文件列表
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.resetForm("importForm");
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.importForm.file = file;
    },
    /** 文件选择处理 */
    handleFileChange(file, fileList) {
      this.importForm.file = file;
    },
    /** 获取当前选中的台账类型名称 */
    getCurrentTypeName() {
      if (!this.activeType || !this.ledgerTypes.length) {
        return "暂无台账类型";
      }
      const currentType = this.ledgerTypes.find(
        (type) => type.value === this.activeType
      );
      return currentType ? currentType.label : "未知类型";
    },
    /** 提交导入 */
    submitImport() {
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          // 检查是否有选择的文件
          if (
            !this.importForm.file &&
            (!this.$refs.upload || !this.$refs.upload.uploadFiles.length)
          ) {
            this.$modal.msgError("请选择要导入的文件");
            return;
          }

          // 获取文件对象
          const file =
            this.importForm.file ||
            (this.$refs.upload ? this.$refs.upload.uploadFiles[0] : null);
          if (!file) {
            this.$modal.msgError("请选择要导入的文件");
            return;
          }

          this.upload.isUploading = true;
          fileImport(file, this.importForm.porjectId, this.activeType)
            .then((response) => {
              this.$modal.msgSuccess("导入成功");
              this.importOpen = false;
              this.resetImport();
              this.getList(); // 刷新列表
            })
            .catch(() => {
              this.upload.isUploading = false;
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-menu {
  border-right: none;
}

.app-container {
  height: calc(100vh - 140px);
  overflow: auto;
  box-sizing: border-box;
  padding-bottom: 24px;
}

// .main-card {
// height: 600px;
// overflow: auto;
// }

::v-deep .el-menu-item {
  position: relative;
}

.type-delete-icon {
  display: none;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.el-menu-item:hover .type-delete-icon {
  display: inline-block;
}

::v-deep .el-menu-item {
  padding-left: 0 !important;
  padding-right: 0 !important;
  width: 100%;
  box-sizing: border-box;
}

::v-deep .el-card__body {
  padding: 8px !important;
}

@media (max-width: 992px) {
  .el-col-sm-24 {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .main-card {
    height: auto !important;
    min-height: 300px;
    overflow: visible;
  }

  .el-card {
    margin-bottom: 12px;
  }
}

@media (max-width: 600px) {
  .app-container {
    padding: 4px;
  }

  .main-card {
    padding: 0 !important;
  }
}

// 移除 ledger-detail-* 相关样式，全部用 daily-detail-*
.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

@media (max-width: 600px) {
  .daily-detail-title {
    font-size: 20px;
  }

  .daily-section-title {
    font-size: 15px;
    padding-left: 8px;
  }

  .daily-detail-table th,
  .daily-detail-table td {
    font-size: 13px;
    padding: 7px 4px;
  }
}

/* 表格行样式 */
::v-deep .row-yellow {
  background-color: #fff3cd !important;
}

::v-deep .row-red {
  background-color: #f8d7da !important;
}

/* 完全去掉表格鼠标移入的默认hover效果 */
::v-deep .el-table__body tr:hover>td {
  background-color: inherit !important;
}

::v-deep .el-table__body tr:hover {
  background-color: inherit !important;
}

/* 确保自定义的行样式在hover时保持不变 */
::v-deep .el-table__body tr.row-yellow:hover>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.row-yellow:hover {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.row-red:hover>td {
  background-color: #f8d7da !important;
}

::v-deep .el-table__body tr.row-red:hover {
  background-color: #f8d7da !important;
}

.custom-menu-item {
  display: flex !important;
  align-items: center;
  //justify-content: space-between;
  position: relative;
  padding-right: 8px;
}

.item-icon {
  margin-right: 0;
  flex-shrink: 0;
}

.item-title-tooltip {
  flex: 1 1 120px;
  max-width: 120px;
  min-width: 0;
  margin-right: 8px;
}

.item-title {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.type-delete-icon {
  color: #f56c6c;
  padding: 0;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
  margin-left: 8px;
}

.custom-menu-item:hover .type-delete-icon {
  opacity: 1;
}

/* 上传组件样式 */
.upload-container {
  width: 100%;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-component {
  width: 100%;
}

/* 上传表单项样式 */
.upload-form-item {
  margin-bottom: 20px;
}

.upload-form-item .el-form-item__content {
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 118px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

::v-deep .upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
}

::v-deep .upload-component .el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  margin: 0;
}

/* 确保上传组件在对话框内不会溢出 */
::v-deep .el-dialog__body .upload-container {
  max-width: 100%;
  box-sizing: border-box;
}

/* 统一上传组件样式，避免双重边框 */
::v-deep .upload-component .el-upload-dragger {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

/* 调整对话框底部按钮区域的上边距 */
::v-deep .el-dialog__footer {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 文件上传组件样式 */
.file-upload-component {
  width: 100%;
}

.file-upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.file-upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

.file-upload-component .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-top: 8px;
}

.file-upload-component .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.file-upload-component .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

/* 文件列表样式 */
.file-upload-component .el-upload-list--text {
  margin-top: 8px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-name {
  color: #606266;
  font-size: 14px;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-status-label {
  color: #67c23a;
  font-size: 12px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-delete {
  color: #f56c6c;
  cursor: pointer;
  font-size: 16px;
}

/* 详情弹窗图片展示样式 */
.image-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 16px 0;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.detail-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

/* 文件展示区域样式 */
.file-display-container {
  margin: 16px 0;
}

.file-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #409eff;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info i {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 项目总含税金额显示样式 */
.amount-total-display {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  min-height: 32px;
}

.amount-value {
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  margin-right: 4px;
}

.amount-unit {
  color: #606266;
  font-size: 14px;
}

/* 项目总金额显示区域样式 */
.amount-display-section {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
}

.amount-display-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}

.amount-display-content {
  display: flex;
  align-items: center;
}

.amount-loading {
  color: #409eff;
  font-size: 14px;
}

.amount-value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.amount-unit {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
}
</style>
